package com.example.opengl.camera.filter

import android.content.Context
import android.opengl.GLES11Ext
import android.opengl.GLES20
import android.opengl.GLES20.*
import android.opengl.Matrix
import com.example.opengl.R
import com.example.opengl.camera.TextureHelper
import javax.microedition.khronos.opengles.GL

/**
 * @author: Mr.You
 * @create: 2023-07-19 11:50
 * @description: 相机渲染
 */
class CameraFilter(

    vertexSourceId: Int = R.raw.camera_vertex,
    fragmentSourceId: Int = R.raw.camera_fragment
) : BaseFilter( vertexSourceId, fragmentSourceId) {
    //FBO缓冲区
    private var mFragmentBuffers: IntArray? = null
    //FBO的纹理id
    private var mFragmentBufferTexture: IntArray? = null
    //变化矩阵
    private var matrix: FloatArray? = null

    override fun onReady(width: Int, height: Int) {
        super.onReady(width, height)
        mFragmentBuffers = intArrayOf(1)
        //创建FBO帧缓冲区
        glGenFramebuffers(mFragmentBuffers!!.size,mFragmentBuffers,0)
        //创建FBO纹理
        mFragmentBufferTexture = intArrayOf(1)
        TextureHelper.getTextures(mFragmentBufferTexture!!)

        //FBO绑定纹理
        glBindTexture(GL_TEXTURE_2D,mFragmentBufferTexture!![0])

        //生成2D纹理图像
        glTexImage2D(GL_TEXTURE_2D,0, GL_RGBA,width,height,0, GL_RGBA, GL_UNSIGNED_BYTE,null)
        //绑定缓冲区
        glBindFramebuffer(GL_FRAMEBUFFER,mFragmentBuffers!![0])

        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,mFragmentBufferTexture!![0],0)

        //解绑操作
        glBindTexture(GL_TEXTURE_2D,0)
        glBindFramebuffer(GL_FRAMEBUFFER,0)

    }

    override fun onDrawFrame(textureId: Int): Int {
        //设置显示窗口大小
        glViewport(0,0,mWidth,mHeight)
        //绑定FBO
        glBindFramebuffer(GL_FRAMEBUFFER,mFragmentBuffers!![0])
        //使用着色器程序
        glUseProgram(mProgramId)
        //赋值给顶点着色器代码
        mVertexBuffer?.position(0)
        glVertexAttribPointer(vPosition,2, GL_FLOAT,false,0,mVertexBuffer)
        glEnableVertexAttribArray(vPosition)
        //赋值给纹理着色器代码
        mTextureBuffer?.position(0)
        glVertexAttribPointer(vCoord,2, GL_FLOAT,false,0,mTextureBuffer)
        glEnableVertexAttribArray(vCoord)

        //变换矩阵
        glUniformMatrix4fv(vMatrix,1,false,matrix,0)
        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,textureId)
        glUniform1i(vTexture,0)
        //启动OpenGL绘制功能
        glDrawArrays(GL_TRIANGLE_STRIP,0,4)

        //解绑
        glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,0)
        glBindFramebuffer(GL_FRAMEBUFFER,0)

        return mFragmentBufferTexture!![0]
    }

     fun setMatrix(matrix: FloatArray){
        this.matrix = matrix
    }

}